package cn.portx.policy;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.bstek.bdf3.dorado.jpa.JpaUtil;
import com.bstek.bdf3.dorado.jpa.policy.impl.GeneratorPolicy;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;

import cn.portx.entity.Order;
import cn.portx.entity.OrderNo;

public class OrderNoGeneratorPolicy implements GeneratorPolicy {

	@Override
	public void apply(Object entity, Field field) {
		Assert.isAssignable(String.class, field.getType(), "Field type must be java.lang.String!");
		boolean isEntity = EntityUtils.isEntity(entity);
		if (isEntity) {
			EntityState state = EntityUtils.getState(entity);
			if (EntityState.NEW.equals(state) && StringUtils.isEmpty(EntityUtils.getString(entity, field.getName()))) {
				EntityUtils.setValue(entity, field.getName(), getOrderNo(((Order) entity).getType()));
			}
		} else {
			field.setAccessible(true);
			try {
				if (field.get(entity) == null) {
					field.set(entity, getOrderNo(((Order) entity).getType()));
				}
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
	}

	public synchronized static String getOrderNo(String type) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(new Date());

		List<OrderNo> list = JpaUtil.linq(OrderNo.class).equal("date", date).equal("type", type).list();
		OrderNo on = null;
		if (list.isEmpty()) {
			on = new OrderNo();
			on.setMaxNum(0);
			on.setDate(date);
			on.setType(type);
			JpaUtil.persist(on);
		} else {
			on = list.get(0);
		}
		long maxNum = on.getMaxNum() + 1;
		on.setMaxNum(maxNum);
		JpaUtil.merge(on);
		JpaUtil.flush(on);
		String orderNo = StringUtils.leftPad(String.valueOf(maxNum), 7, "0");
		return ("0".equals(type) ? "CK" : "JK") + date + orderNo;
	}

}
